<template>
  <a-card class="arrive_main">
    <a-spin :spinning="spinning">
      <div class="arrive_head">
        <div class="arrive_head_left">
          <!-- <a-button slot="extra" class="btn_normal_color arrive_delete_btn" alt="返回按钮" style="margin-right: 20px;" @click="backRouter"> 返回</a-button> -->
          <!-- <div @click="backRouter" class="arrive_head_left_cancel"> <a-icon type="arrow-left" style="margin-right: 16px;"/> 返回 </div>-->
          <a-button @click="backRouter" type="text" size="large" style="font-weight: 550; font-size: 1.2rem;border: none;margin: 0;padding: 0px 0px 0px 0px;">
            <a-icon type="arrow-left" />
            返回
          </a-button>
          <a-divider type="vertical" style=" height: 18px;margin: 0px 16px;" />
          <div class="arrive_head_left_label">文书送达</div>
          <div class="arrive_head_left_code"> 案号: <span style="margin-left: 20px">{{ acceptcode }}</span></div>
          <div class="arrive_head_left_code" v-if="status_text"> 状态: <div class="arrive_head_left_status"> {{ status_text }}</div> </div>
        </div>
        <div class="arrive_head_right">
          <a-button v-if="tabKey == 'undo'" type="primary" icon="reconciliation" class="arrive_content_buttons_style_blue btn_primary_color" :loading="loading" @click="addDetail">新增送达</a-button>
          <!-- <page-header-wrapper :title="false"></page-header-wrapper> -->
          <!-- <img class="cursor_pointer" src="@/assets/images/accept/back-button.png" alt="返回按钮" @click="backRouter"> -->
        </div>
      </div>
      <div class="arrive_content">
        <a-tabs default-active-key="undo" class="arrive_content_tabs" v-model="tabKey">
          <a-tab-pane key="undo" force-render>
            <span slot="tab" class="arrive_content_tabs_customer">
              待送达
              <a-badge
                v-if="undoNum > 0"
                :count="undoNum"
                :number-style="{
                  backgroundColor: '#CA0000',
                  color: '#ffffff',
                  fontSize: '14px',
                  width: '18px',
                  height: '18px',
                  lineHeight: 'unset',
                  minWidth: '18px',
                  padding: '2px 0px'
                }"
              />
            </span>
            <ArriveInfoTodo :key="Math.random()" :applyid="applyid" @reload="getArriveDetailsById" @saveSingleTemp="saveSingleTemp" ref="arriveInfoTodo"></ArriveInfoTodo>
          </a-tab-pane>
          <a-tab-pane key="done" force-render>
            <span slot="tab" class="arrive_content_tabs_customer">
              已送达
              <a-badge
                v-if="doneNum > 0"
                :count="doneNum"
                :number-style="{
                  backgroundColor: '#CA0000',
                  color: '#ffffff',
                  fontSize: '14px',
                  width: '18px',
                  height: '18px',
                  lineHeight: 'unset',
                  minWidth: '18px',
                  padding: '2px 0px'
                }"
              />
            </span>
            <ArriveInfoDone :key="Math.random()" ref="arriveInfoDone"></ArriveInfoDone>
          </a-tab-pane>
          <!-- <template slot="tabBarExtraContent">
            <div class="arrive_content_buttons" v-if="tabKey == 'undo'">
              <a-button icon="save" class="arrive_content_buttons_style_blue btn_primary_color" :loading="loading" @click="saveTemp">暂存信息</a-button>
              <a-button icon="twitter" class="arrive_content_buttons_style_white btn_normal_color" :loading="loading" @click="oneKeySend">一键送达</a-button>
            </div>
          </template> -->
        </a-tabs>
      </div>

      <div class="arrive_content_buttons" v-if="tabKey == 'undo'">
        <a-button class="arrive_content_buttons_style_blue btn_primary_color" type="primary" icon="save" style="width:120px" :loading="loading" @click="saveTemp">暂存信息</a-button>
        <a-button class="arrive_content_buttons_style_white btn_normal_color" style="width:120px" :loading="loading" @click="oneKeySend">
          <img src="~@/assets/images/accept/send.svg" style="width:14px;height: 14px;margin-right: 10px;" />
          一键送达
        </a-button>
      </div>
    </a-spin>
    <ArriveInfoAddModal ref="arriveInfoModal" @reload="getArriveDetailsById" :applyid="applyid"></ArriveInfoAddModal>
  </a-card>
</template>

<script>
import storage from 'store'
import { APP_USER, APP_DEPT } from '@/store/mutation-types'
import { getArriveDetailsById } from '@/api/arrive/apl_arrive_main'
import { saveTemp, saveSend, getReviewDetailByApplyid } from '@/api/arrive/apl_arrive_details'
import { St_arriveValue } from '@/enumeration/St_arrive'

import moment from 'moment'
export default {
  data () {
    return {
      tabKey: 'undo',
      spinning: false,
      applyid: undefined, // applyid
      acceptcode: undefined, // 案号
      status: undefined, // 状态
      status_text: undefined, // 状态文本
      St_arriveValue: St_arriveValue,
      loading: false,
      currentUser: storage.get(APP_USER), // 登录人信息
      currentDept: storage.get(APP_DEPT), // 登录人部门
      undoNum: 0,
      doneNum: 0,

      recipientnameOption: [],
      // 默认人员信息：
      // 申请人信息
      applicantList: [],
      // 代理人信息
      agentList: [],
      // 被申请人信息
      targetList: [],
      // 第三人信息
      thirdList: []
    }
  },
  async created () {
    this.applyid = this.$route.params.applyid
    this.acceptcode = this.$route.query.queryParam.acceptcode
    this.status = this.$route.query.queryParam.status
    this.status_text = this.$route.query.queryParam.status_text
    this.warntime = this.$route.query.queryParam.warntime
    this.leftDay = this.$route.query.queryParam.leftDay

    this.$store.commit('SET_BASIC_INFO', ['applyid', this.applyid])
    this.$store.commit('SET_BASIC_INFO', ['acceptcode', this.acceptcode])
    this.$store.commit('SET_BASIC_INFO', ['status', this.status])
    this.getArriveDetailsById()
    this.tabKey = 'undo'

    this.getDefaultPersonInfo()
  },
  components: {
    ArriveInfoTodo: () => import('@/views/arrive/ArriveInfoTodo.vue'),
    ArriveInfoDone: () => import('@/views/arrive/ArriveInfoDone.vue'),
    ArriveInfoAddModal: () => import('@/views/arrive/ArriveInfoAddModal.vue')
  },
  methods: {
    backRouter () {
      if (this.$route.query.url) {
        let queryParam = JSON.parse(JSON.stringify(this.$route.query.queryParam))
        queryParam = Object.keys(queryParam).length != 0 ? queryParam : {}
        this.$router.push({
          path: this.$route.query.url,
          query: {
            queryParam: queryParam
          }
        })
        console.log('this.$route.query.queryParam', this.$route.query.queryParam)
      } else {
        this.$router.go(-1)
      }
    },
    // 查询对应applyid的详情数据
    getArriveDetailsById () {
      getArriveDetailsById(this.applyid).then(res => {
        if (res.code === 0) {
          const arriveList = res.data
          let undoList = []
          let doneList = []
          if (arriveList && arriveList.length > 0) {
            undoList = arriveList.filter(el => el.sendstatus == 3201)
            if (undoList && undoList.length > 0) {
              undoList.forEach(undo => {
                if (undo.warntime) {
                  undo.leftDay = moment(undo.warntime).diff(moment(new Date()), 'days')
                }
              })
            }
            doneList = arriveList.filter(el => el.sendstatus == 3200)
          }
          this.undoNum = undoList.length
          this.doneNum = doneList.length
          this.$store.commit('SET_UNDO_LIST', undoList)
          this.$store.commit('SET_DONE_LIST', doneList)
        } else {
          this.$message.error('送达详情数据查询失败')
        }
      }).finally(() => { this.spinning = false })
    },
    async getDefaultPersonInfo () {
      const res = await getReviewDetailByApplyid(this.applyid)
      if (res.code == 0) {
        const resObj = res.data
        this.recipientnameOption = []
        if (resObj != null && resObj != undefined) {
            // 被申请人信息：
            this.targetList = resObj.targetList
            // 申请人信息
            this.applicantList = resObj.applicantList
            // 代理人信息
            this.agentList = resObj.agentList
            // 第三人信息
            this.thirdList = resObj.thirdList
            // 送达信息
            this.arriveInfo = resObj.arriveInfo

            if (this.applicantList) {
              this.applicantList.forEach((item) => {
                item.label = '申请人-' + item.name
                item.personType = 'applicant'
                this.recipientnameOption.push(item)
              })
            }
            if (this.agentList) {
              this.agentList.forEach((item) => {
                item.label = '代理人-' + item.name
                item.personType = 'agent'
                this.recipientnameOption.push(item)
              })
            }
            if (this.targetList) {
              this.targetList.forEach((item) => {
                item.label = '被申请人-' + item.name
                item.personType = 'target'
                this.recipientnameOption.push(item)
              })
            }
            if (this.thirdList) {
              this.thirdList.forEach((item) => {
                item.label = '第三人-' + item.name
                item.personType = 'third'
                this.recipientnameOption.push(item)
              })
            }
            // 将数据插入到缓存中
            this.$store.commit('SET_RECIPIENTNAME_OPTION', this.recipientnameOption)
          }
      } else {
        this.$message.error('获取默认人员信息失败')
      }
    },
    // 新增一条详情数据
    addDetail () {
      this.$refs.arriveInfoModal.init()
    },
    // 一键送达
    oneKeySend () {
      this.$confirm({
        title: '是否一键送达数据',
        onOk: () => {
          // 校验信息是否都填写成功
          if (this.$refs.arriveInfoTodo.validateForm()) {
            // 信息填写完成后 获取对应的信息
            const undoList = this.$refs.arriveInfoTodo.getCheckList()
            // 判断是否都有送达人信息，若无则提示无法送达
            if (undoList && undoList.length > 0) {
              let isValid = true
              undoList.forEach(undo => {
                if (!(undo.personList && undo.personList.length > 0)) {
                  isValid = false
                }
              })
              if (!isValid) {
                this.$message.error('请填写送达人信息')
                return
              }
              this.loading = true
              saveSend(undoList, this.currentUser.userId, this.currentUser.fullname).then((res) => {
                if (res.code !== 0) {
                  this.$message.error('一键送达失败')
                } else {
                  this.$message.success('一键送达成功')
                  // 重新加载数据
                  this.getArriveDetailsById()
                }
              }).finally(() => {
                this.loading = false
              })
            } else {
              this.$message.error('请填写送达人信息')
            }
            // 保存人员数据
          } else {
            this.$message.error('请填写完整信息')
          }
        }
      })
    },
    // 暂存数据
    saveTemp () {
      // 获取对应的数据
      const undoList = this.$refs.arriveInfoTodo.getUndoList()
      if (undoList && undoList.length > 0) {
        this.loading = true
        this.spinning = true
        saveTemp(undoList).then((res) => {
          if (res.code !== 0) {
            this.$message.error('暂存失败')
          } else {
            this.$message.success('暂存成功')
            // 重新加载数据
            this.getArriveDetailsById()
          }
        }).finally(() => {
          this.loading = false
          this.spinning = false
        })
      }
    },

    // 保存当前数据
    saveSingleTemp (detailId) {
      let undoList = this.$refs.arriveInfoTodo.getUndoList()
      undoList = undoList.filter(el => el.id == detailId)
      if (undoList && undoList.length > 0) {
        this.loading = true
        this.spinning = true
        saveTemp(undoList).then((res) => {
          if (res.code !== 0) {
            this.$message.error('保存失败')
          } else {
            this.$message.success('保存成功')
            // 重新加载数据
            this.getArriveDetailsById()
          }
        }).finally(() => {
          this.loading = false
          this.spinning = false
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>

  ::v-deep .ant-pro-page-header-wrap {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: auto;
  }

  .arrive_main {
    display: flex;
    align-content: center;
    justify-content: center;
    flex-direction: column;

    ::v-deep .ant-card-body {
      padding: 16px 16px;
    }
  }

  .arrive_head {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    height: 36px;

    &_left {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-right: auto;
      // flex: 3;

      &_cancel {
        cursor: pointer;
        color: rgb(162, 162, 162);
        font-size: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      &_label {
        font-family: Source Han Sans CN;
        font-weight: 800;
        font-size: 18px;
        color: #2C2C2C;
        margin-right: 60px;
        align-items: center;
      }

      &_code {
        display: flex;
        font-family: Source Han Sans CN;
        font-weight: 500;
        font-size: 16px;
        color: #2C2C2C;
        margin-right: 60px;
        align-items: center;
      }

      &_status {
        display: flex;
        align-content: center;
        justify-content: center;
        align-items: center;

        width: 100px;
        height: 28px;
        background: rgba(255,200,44,0.1);
        border-radius: 14px;
        border: 1px solid #E3A800;
        margin-left: 20px;

        font-family: Source Han Sans CN;
        font-weight: 500;
        font-size: 16px;
        color: #E3A800;
        line-height: 7px;
      }
    }

    &_right {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      // flex: 2;
    }
  }
  .arrive_content {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    width: 100%;
    margin-top: 20px;

    &_tabs {
      width: 100%;

      &_customer {
        display: flex;
        justify-content: space-around;
        align-items: center;
        width: 85px;
      }
    }

    &_buttons {
      display: flex;
      flex-direction: row;
      align-items: center;
      cursor: pointer;
      height: 60px;
      margin-top: 20px;
      float: right;

      &_style_blue {
        width:108px;
        background-color:#0072C6;
        border-color: #0072C6;
        margin: 0px 10px;
        color: #ffffff
      }

      &_style_white {
        width:108px;
        background-color: #ffff;
        border-color: #0072C6;
        color: #0072C6;
        margin: 0px 10px;
      }
    }
  }
</style>
